from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
#from ragendja.template import render_to_response
from django.template import RequestContext
from django.contrib.auth.models import User,AnonymousUser

from realpython.joke.models import *
from realpython.index.functions import *


def joke_add(request):
    if request.method == 'POST':
        form = JokeForm(request.POST)
        if form.is_valid():
            #form.save()
            content = form.cleaned_data['content']
            if request.user.is_authenticated():
                sender = request.user
            else:
                sender = None
            joke = Joke.create(content, sender)
            create_message(request, 'Thanks for posting joke!')
            form = JokeForm()
            #return HttpResponseRedirect('/joke/add/')
        else:
            create_message(request, 'Error happens', 'error')
    else:
        form = JokeForm()
    
    return render_to_response('joke_add.html', {'form': form}, context_instance=RequestContext(request))
        
def display_joke(request):
    return {
        'joke': Joke.get_by_random(),
    }

